package com.web;

import com.domain.User;
import com.service.userService;
import org.apache.commons.beanutils.BeanUtils;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

/**
 * 员工添加客户
 * 接收addUser.jsp页面的数据，封装成User对象
 * 提交到userService的addUser函数
 * 重定向到/showUser
 */
@WebServlet("/addUser")
public class addUserServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.解决乱码
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=UTF-8");

        //2.接收参数
        Map<String, String[]> map = request.getParameterMap();

        //3.封装对象
        User user = new User();

        try {
            BeanUtils.populate(user,map);
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("添加了 "+ user +" 用户");
        //4.调用service层,存入数据库
        new userService().addUser(user);

        //5.重新查询所有,回到页面
        response.sendRedirect(request.getContextPath()+"/showUser");//重定向

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }
}
